package com.ukao.steward.ui.valetRunners.storage;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ukao.steward.R;
import com.ukao.steward.adapter.PhotoAdapter;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.ProductRelImgBean;
import com.ukao.steward.bean.StorageListBean;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.MyLRecyclerView;
import com.ukao.steward.widget.StateButton;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.steward.R.id.storge_go_btn;
import static com.ukao.steward.consts.Constant.ARG_PARAM3;
import static com.ukao.steward.consts.Constant.REQUEST_CODE;


public class PhotoFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.take_picture_btn)
    StateButton takePictureBtn;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.lrecycler_view)
    MyLRecyclerView lrecyclerView;
    @BindView(storge_go_btn)
    Button storgeGoBtn;
    Unbinder unbinder;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private PhotoAdapter mPhotoAdapter;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;

    private ArrayList<ProductRelImgBean> mProductRelImgData;
    private boolean isloadFinish;
    private View mEmptyView;


    private  StorageListBean.ProListBean  mProBean;

    public static PhotoFragment newInstance(StorageListBean.ProListBean  mProBean) {
        PhotoFragment fragment = new PhotoFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, mProBean);

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mProBean= getArguments().getParcelable(ARG_PARAM1);


        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_photo, container, false);
        unbinder = ButterKnife.bind(this, view);
        mEmptyView= view.findViewById(R.id.empty_view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (!isloadFinish){
            lrecyclerView.forceToRefresh();
        }

    }

    @Override
    protected void initView() {
        if (mProBean!=null){
            title.setText(CheckUtils.isEmptyString(mProBean.getProductName()));

        }

        storgeGoBtn.setText(R.string.save_upload);
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        GridItemDecoration divider = new GridItemDecoration.Builder(_mActivity)
                .setHorizontal(R.dimen.dp_10)
                .setVertical(R.dimen.dp_10)
                .setColorResource(R.color.transparent)
                .build();
        mProductRelImgData=new ArrayList<>();
        initGridRecyclerView(lrecyclerView,4);
        mPhotoAdapter= new PhotoAdapter(_mActivity, mProductRelImgData);
        mLRecyclerViewAdapter= new LRecyclerViewAdapter(mPhotoAdapter);
        lrecyclerView.setAdapter(mLRecyclerViewAdapter);
        lrecyclerView.addItemDecoration(divider);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mLRecyclerViewAdapter.setOnItemClickListener((view1, i) -> {
          ActivityUtils.JumpPhotoListActivity(_mActivity,i,(ArrayList)mPhotoAdapter.getDataList());

        });
        mPhotoAdapter.setOnItemChildClickListener((id, pos, item) -> {
            switch (id) {
                case R.id.remove_image:
                    ProductRelImgBean mItem = mPhotoAdapter.getItem(pos);
                    if (mItem != null) {
                        deleteRelImg(mItem);
                    }
                    break;
            }

        });
        lrecyclerView.setOnRefreshListener(() -> {
            productImagelist(mProBean.getId());
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.back_btn, R.id.take_picture_btn, storge_go_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                setFragmentResult();
                break;
            case R.id.take_picture_btn:

                Intent intent =  ActivityUtils.JumpCameraActivity(_mActivity);
                intent.putExtra(ARG_PARAM1, mProBean.getId());
                intent.putExtra(ARG_PARAM2, (ArrayList)mPhotoAdapter.getDataList());
                intent.putExtra(ARG_PARAM3, mProBean.getPicCnt());
                startActivityForResult(intent, REQUEST_CODE);
                break;
                case storge_go_btn:


                break;
        }
    }

    /**
     * 查询衣物图片列表
     * @param id
     */
    public void productImagelist( final String  id) {

        HashMap mHashMap=new HashMap<String,String>();
        mHashMap.put("orderProId",id);/*订单衣物id*/
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().productlist(Constant.createParameter(mHashMap)),
                new ApiCallback<ProductRelImgBean>() {
                    @Override
                    public void onSuccess(ProductRelImgBean model) {
                        if (model.getHttpCode()==200){
                            isloadFinish=true;
                            mPhotoAdapter.setDataList(model.getData());
                             int    photoCnt=model.getData().size();
                            mProBean.setPicCnt(photoCnt);
                            mEmptyView.setVisibility(CheckUtils.isEmpty(model.getData())?View.VISIBLE:View.GONE);
                        }else{
                            T.show(model.getMsg());

                        }


                    }



                    @Override
                    public void onFinish() {
                        lrecyclerView.refreshFinish();
                    }

                });
    }


    @Override
    public boolean onBackPressedSupport() {
        setFragmentResult();

        return true;
    }

    void setFragmentResult() {
        Bundle mBundle=new Bundle();
        mBundle.putParcelable(ARG_PARAM1,mProBean);
        setFragmentResult(RESULT_OK,mBundle);
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE:/*获取照片数量*/
                    isloadFinish=false;
                  int   photoCnt = data.getIntExtra(ARG_PARAM1, 0);
                    mProBean.setPicCnt(photoCnt);
                    lrecyclerView.forceToRefresh();


                    break;

            }
        }
    }

        /**
     删除衣物照片
     */
    public void deleteRelImg(final ProductRelImgBean item    ) {
       showProgressDialog();
        String cameraImg=item.getCameraImg();
        if (!CheckUtils.isEmpty(cameraImg) && !cameraImg.substring(0, 4).equals("http")) {

        }else{
            HashMap mHashMap=new HashMap<String,String>();
            mHashMap.put("id", String.valueOf(item.getId()));/*衣物图片的id*/
            mHashMap.put("accessToken", SaveParams.getToken());
            addSubscription(apiStores().deleteRelImg(Constant.createParameter(mHashMap)),
                    new ApiCallback<StringBean>() {
                        @Override
                        public void onSuccess(StringBean model) {

                            if (model.getHttpCode()==200){

                                int indexOf = mPhotoAdapter.getDataList().indexOf(item);
                                if (indexOf != -1) {
                                    mPhotoAdapter.getDataList().remove(indexOf);
                                    mPhotoAdapter.notifyItemRemoved(indexOf);
                                    mProBean.setPicCnt( mPhotoAdapter.getDataList().size());
                                }

                                mEmptyView.setVisibility(CheckUtils.isEmpty(mPhotoAdapter.getDataList())?View.VISIBLE:View.GONE);

                            }else{
                                T.show(model.getMsg());
                            }

                        }



                        @Override
                        public void onFinish() {
                           dismissProgressDialog();

                        }

                    });
        }

    }

}
